var http = require('http')
var querystring = require('querystring');
var iconv = require('iconv-lite');
var fs = require('fs');

var PROXY_HOST = 'dev-proxy.oa.com';
var PROXY_PORT = '8080';

function query_wb_code(hz, callback) {
    console.log(hz);
    var gbk = iconv.encode(hz, 'GBK');
    var post_data = 'hzname=' + '%' + gbk[0].toString(16) + '%' + gbk[1].toString(16);//%D9%D7';

    var opt = {
        host:PROXY_HOST,
        port:PROXY_PORT,
        method:'POST',
        path:'http://52wubi.com/wbbmcx/search.php',
        headers:{
           'Content-Type': 'application/x-www-form-urlencoded',
           'Content-Length': Buffer.byteLength(post_data)
        }
    };
    
    const regex = /<td class="wbbm">([a-zA-Z]+)<\/td>/g;
    var body = '';
    var req = http.request(opt, function(res) {
        // console.log("Got response: " + res.statusCode);
        res.on('data',function(d){
        body += d;
    }).on('end', function(){
        // console.log(res.headers)
        // var utf8_body = iconv.decode(body, 'GBK');
        var match = regex.exec(body);
        if (match && match.length > 0) {
            console.log('wbbm is : ' + match[1]);
            fs.appendFileSync('wbcode.txt', hz + ',' + match[1] + '\n');
        } else {
            console.log('error : no wbbm');
            // var utf8_body = iconv.decode(body, 'utf-8');
            // console.log(utf8_body);
        }
        callback();
        // console.log(body)
    });

    }).on('error', function(e) {
        console.log("Got error: " + e.message);
        callback();
    })
       
    req.write(post_data);
    req.end();
}

function download_wb_pic(hz, callback) {
    var pic_path = 'http://52wubi.com/wbbmcx/tp/' + querystring.escape(hz) + '.gif';
    var opt = {
        host:PROXY_HOST,
        port:PROXY_PORT,
        method:'GET',
        path:pic_path,
        headers:{
            'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4033.400 QQBrowser/9.6.12624.400',
            "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Encoding":"gzip, deflate, sdch",
            "Accept-Language":"zh-CN,zh;q=0.8"
        }
    };    

    var ws = fs.createWriteStream('pic/' + hz +'.gif');
    http.get(opt).on('response', function (response) {
        response.on('data', function (chunk) {
            ws.write(chunk);
        });
        response.on('end', function () {
            console.log('Finished');
            ws.end();
            callback();
        });
    }).on('error', function(e) {
        console.log("Got error: " + e.message);
        callback();
    });
}

// function query_wb(hz) {
//     query_wb_code(hz);
//     download_wb_pic(hz);
// }

var hzs = fs.readFileSync('t.txt', 'utf-8');
var query_index = 0;
function query_next() {
    if (query_index >= hzs.length) {
        return false;
    }

    console.log('query_index = ' + query_index.toString());

    query_wb_code(hzs[query_index], function() {
        query_index += 1;
        process.nextTick(query_next);
    })
}

query_next();

// query_wb('中');

